import { getURLParams } from './getURLParams.mjs'
import { $ } from './dom.mjs'

const Demos = [
  { label: '3D 文字', path: '/3d-letter' },
  { label: '3D Progress', path: 'https://codepen.io/rgg/embed/QbRyOq?default-tab=html%2Cresult' },
  { label: 'Switch', path: '/ui-switch' },
  { label: 'VueRouter', path: '/vue-router' },
]

const viewDomNode = $('.view')
const placeholderDomNode = $('.placeholder')
placeholderDomNode.textContent = 'Open'
viewDomNode.appendChild(placeholderDomNode)

const sideDomNode = $('aside.menu')
Demos.forEach((demo, index) => {
  const buttonDomNode = $('button.menu-item', {
    role: 'button',
    onclick: () => {
      openWebview(demo.path)
      location.search = `id=${index + 1}`
    },
  })
  buttonDomNode.textContent = demo.label
  sideDomNode.appendChild(buttonDomNode)
})

const wrapDomNode = $('.workbench', null, sideDomNode, viewDomNode)
document.body.appendChild(wrapDomNode)

requestAnimationFrame(() => {
  const params = getURLParams()
  const id = Number(params.id) - 1
  const target = Demos[id]
  target && openWebview(target.path)
})

function openWebview(src) {
  let iframe = viewDomNode.querySelector('iframe')

  if (!iframe) {
    iframe = $('iframe', {
      loading: 'lazy',
      frameborder: '0',
      allowfullscreen: 'true',
    })
    viewDomNode.replaceChild(iframe, placeholderDomNode)
  }

  iframe.src = src.startsWith('http') ? src : `./demo${src}`

  return iframe
}
